package com.gitee.cashzhang27.test.boot.other.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.colors.Color;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.canvas.draw.ILineDrawer;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.LineSeparator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.Map.Entry;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Cash Zhang
 * @since 2018/12/13
 */
@RequestMapping("/iText")
@RestController
@Api(value = "ITextController", description = "IText测试")
public class ITextController {
  //    private final static String SRC =
  // "D:/workspace/git/idea/springboot/springboot-itext/src/main/resources/template/备案申请书.html";
  public static final String FONT =
      "D:/workspace/git/idea/springboot/springboot-itext/src/main/resources/font/NotoSansCJKsc-Regular.otf";
  //  private static final String DEST = "C:/Users/cashZhang/Desktop/temp/备案申请书.pdf";
  //  private static final String SRC =
  //
  // "D:/workspace/git/idea/springboot/springboot-itext/src/main/resources/template/755b3e89fe9b11e89fdd6ba2fe9176cd.html";
  private static final String SRC = "/usr/local/src/6be868923a1b4fefb3dddcd77767afb5.pdf";
  private static final String DEST = "/usr/local/src/test1.pdf";

  @GetMapping("/html2pdf")
  @ApiOperation(value = "html转pdf")
  public void html2pdf(String htmlPath, String pdfPath) throws IOException {
    this.tomPdf(SRC, DEST);
  }

  public void tomPdf(String html, String DEST) throws FileNotFoundException, IOException {
    ConverterProperties props = new ConverterProperties();
    DefaultFontProvider defaultFontProvider = new DefaultFontProvider(false, false, false);
    defaultFontProvider.addFont(FONT);
    props.setFontProvider(defaultFontProvider);
    PdfWriter writer = new PdfWriter(DEST);
    PdfDocument pdf = new PdfDocument(writer);
    pdf.setDefaultPageSize(new PageSize(595, 14400));
    Document document = HtmlConverter.convertToDocument(new FileInputStream(html), pdf, props);
    // 将所有内容在一个页面显示
    EndPosition endPosition = new EndPosition();
    LineSeparator separator = new LineSeparator(endPosition);
    document.add(separator);
    document.getRenderer().close();
    PdfPage page = pdf.getPage(1);
    float y = endPosition.getY() - 36;
    page.setMediaBox(new Rectangle(0, y, 595, 14400 - y));
    document.close();
    pdf.close();
  }

  /** 生成PDF. */
  @SneakyThrows
  @GetMapping("generate")
  public void generate() {
    // 内存流
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    PdfReader pdfReader = new PdfReader(SRC);
    PdfWriter pdfWriter = new PdfWriter(bos);

    PdfDocument pdfDocument = new PdfDocument(pdfReader, pdfWriter);
    PdfAcroForm pdfAcroForm = PdfAcroForm.getAcroForm(pdfDocument, true);

    ClassPathResource resource = new ClassPathResource("font/Simsun.ttc");

    // 宋体
    PdfFont simsunTtcFont =
        PdfFontFactory.createTtcFont(
            IoUtil.readBytes(resource.getStream()), 1, PdfEncodings.IDENTITY_H, false, true);
    Map<String, PdfFormField> formFields = pdfAcroForm.getFormFields();
    int i = 0;
    for (Entry<String, PdfFormField> entry : formFields.entrySet()) {
      PdfFormField pdfFormField = entry.getValue();
      boolean required = pdfFormField.isRequired();
      if (!required) {
        continue;
      }
      i++;
      pdfFormField.setValue("测试" + i + 1, simsunTtcFont, Float.parseFloat("14"));
    }
    // 将表单域中的value嵌入到pdf文件中
    pdfAcroForm.flattenFields();
    // 关闭流
    pdfDocument.close();

    pdfWriter.close();

    OutputStream out = new FileOutputStream(DEST);
    bos.writeTo(out);
    out.flush();
    out.close();
  }

  class EndPosition implements ILineDrawer {

    /** A Y-position. */
    protected float y;

    /**
     * Gets the Y-position.
     *
     * @return the Y-position
     */
    public float getY() {
      return this.y;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * com.itextpdf.kernel.pdf.canvas.draw.ILineDrawer#draw(com.itextpdf.kernel.pdf.
     * canvas.PdfCanvas, com.itextpdf.kernel.geom.Rectangle)
     */
    @Override
    public void draw(PdfCanvas pdfCanvas, Rectangle rect) {
      this.y = rect.getY();
    }

    /*
     * (non-Javadoc)
     *
     * @see com.itextpdf.kernel.pdf.canvas.draw.ILineDrawer#getColor()
     */
    @Override
    public Color getColor() {
      return null;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * com.itextpdf.kernel.pdf.canvas.draw.ILineDrawer#setColor(com.itextpdf.kernel.
     * color.Color)
     */
    @Override
    public void setColor(Color color) {}

    /*
     * (non-Javadoc)
     *
     * @see com.itextpdf.kernel.pdf.canvas.draw.ILineDrawer#getLineWidth()
     */
    @Override
    public float getLineWidth() {
      return 0;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.itextpdf.kernel.pdf.canvas.draw.ILineDrawer#setLineWidth(float)
     */
    @Override
    public void setLineWidth(float lineWidth) {}
  }
}
